#####
# VERY simple boot loader for X86 machines
# Taken almost verbatim from: 
#   http://www.websofia.com/2011/10/writing-your-own-boot-loader-for-a-toy-operating-system-1/
# Programmer: Pete Lutz
# Date: 6-11-2012 xxx
#####
		.code16			# 16-bit or 'real' mode
		.intel_syntax noprefix	# use std INTEL syntax
		.text			# place this code in the text or code segment
		.org 0x0		# origin is at address 0

LOAD_SEGMENT = 0x1000			# where the 2nd stage boot loader goes
FAT_SEGMENT  = 0x0ee0			# segment for loading in the FAT to access the disk

#####
# M A I N
# Main program of boot loader
# Just jumps around the boot parameter block (BPB) and extended boot
# parameter block (EBPB)
#####
		.global main		# globally accessible label
main:					# entry point
		# These two instructions take up 3 bytes so that the BPB
		# (see bootsector.s) starts at location 0x3
		jmp 	short start	# jump to 'start'
		nop

		# The BPB ane EBPB are read from the boot sector
		# bootsector.s maps this memory to named variables
		.include "bootsector.s"

		# Macros useful for certain operations
		# Include, zero segment registers, reset the disk drive,
		# reboot the system, write a string to the console, find
		# a file (assumes FAT F/S)
		.include "macros.s"

#####
# s t a r t
# The actual start of the boot loader
#####
start:		# actual start of code
		mInitSegments				# Init segment regs to 0
		mResetDiskSystem			# Reset boot disk drive
		mWriteString loadmsg			# Write the Loading ... message
		mFindFile filename, LOAD_SEGMENT	# Find a file names 'filename'
		mReadFAT FAT_SEGMENT			# Read in FAT
		mReadFile LOAD_SEGMENT, FAT_SEGMENT	# Read in 'filename' at location LOAD_SEGMENT
		mStartSecondStage			# Start 2nd stage boot at location LOAD_SEGMENT

#####
# b o o t F a i l u r e
# Boot failed
#####
bootFailure:	
		mWriteString diskerror			# Write error message
		mReboot					# Reboot the machine

		# Include useful functions ... some called by the macros above
		# Includes: Write a string to the console, Reboot the computer,
		# Read a sector from the disk
		.include "functions.s"

#####
# Data for main program
#####
filename:	.asciz	"2NDSTAGEBIN"	# filename of 2nd stage boot loader in FAT F/S
loadmsg:	.asciz	"Loading Simple OS...\r\n"
diskerror:	.asciz	"Disk error. "	# 12-byte message
rebootmsg:	.asciz	"Press any key to reboot.\r\n"

root_strt:	.byte	0,0		# holds offset of root directory on disk
root_scts:	.byte	0,0		# holds # of sectors in root directory
file_strt:	.byte	0,0		# holds offset of bootloader on disk

#####
# Fill
#####
		.fill	(510-(.-main)), 1, 0
					# Pad memory with zeros up to 510 bytes
BootMagic:	.int	0xaa55		# magic word for BIOS (MBR signature)
